<?php
namespace app\common\controller;
use think\Controller;
use think\Db;
use think\Cache;
class WeiXin extends Controller
{
    // 通过code获取公众号的openid
    public function getMpOpenid($config,$wechatCode)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        // 参数
        $params['appid']= $config['appid'];
        $params['secret']= $config['appsecret'];
        $params['code']= $wechatCode;
        $params['grant_type']= 'authorization_code';        

        // 微信API返回的session_key 和 openid
        $arr = httpCurl($url, $params, 'GET');
        $arr = json_decode($arr,true);

        return $arr;
    }
    
    // 通过 获取用户的access_token和openid微信昵称和头像
    public function getUserInfo($access_token,$openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo";

        $params['lang']= 'zh_CN';
        $params['access_token']= $access_token;
        $params['openid']= $openid;        

        $arr = httpCurl($url, $params, 'GET');
        $arr = json_decode($arr,true);

        return $arr;
    }

    // 获取公众号token
    public function getMpToken($appid=null,$appsecret=null)
    {
        // Cache::rm('mpToken');
        # 请求公众号接口
        if (!Cache::get('mpToken')) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
            $token = getJson($url);
            Cache::set('mpToken', $token['access_token'], 600);
        }
        $access_token = Cache::get('mpToken');

        // $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret."";
        // $res = http_request($url,null);
        // $result = json_decode($res,true);
        return $access_token;
    }


    // 发送公众号模板消息
    public function sendMessage($config,$rawData)
    {
        $token = $this->getMpToken($config['appid'],$config['appsecret']);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;

        $res = http_request($url,$rawData);
        return $res;
        // return json_decode($res,true);
    }

    // 获取用户公众号的信息
    public function getUserMpInfo($config,$openid)
    {
        $token = $this->getMpToken($config['appid'],$config['appsecret']);
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";

        $res = http_request($url,$openid);
        return json_decode($res,true);
    }


    // 拉去公众号所有关注者的openid
    public function getUser($token,$nextOpenid = false)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$token;
        if($nextOpenid) $url .= '&next_openid='.$nextOpenid;
        $res = http_request($url,null);
        return json_decode($res,true);
    }
    

}
